package GDoc::Job::Fetch::US::Judi::USCA::USCA01;

use Moose;
use GDoc::Job;
use HTML::TableContentParser;
use File::Temp;

extends 'GDoc::Job::Fetch';


sub setup { 
    my $self = shift;

    $self->_baseurl( 'http://www.ca1.uscourts.gov/pdf.opinions/' );
}


sub run { 
    my $self = shift;

    if ( $self->data->{link} ) { 
        $self->_fetch_pdf;
    } else { 
        my $mech = $self->_mech;
        $mech->get( $self->_baseurl );

        my @links = $mech->find_all_links( text_regex => qr{^\d{2}-\d{4}-01A\.pdf} );
        foreach my $link( @links ) { 
            my $job = GDoc::Job->new( class => 'Fetch::US::Judi::USCA::USCA01',
                                      queue => $self->fetch_queue,
                                      data  => { link => $self->_baseurl . $link->url }
                                    );

            $job->submit;
        }
    }
}


sub _fetch_pdf { 
    my $self = shift;
    my %data = %{ $self->data };

    $data{link} =~ m{(?<year>\d{2})-(?<num>\d{4})-01A\.pdf};
    my ( $year, $num ) = @+{ 'year', 'num' };

    my $fyear = $year < 50 ? ( $year + 2000 ) : ( $year + 1900 );    # srsly :\
    my $mech = $self->_mech;

    my $ident = sprintf( 'USCA01-OP-%04d-%04d', $fyear, $num );
    my $filename = $ident . '.pdf';
    my $key = 'us/judi/usca/usca01/' . $filename;

    if ( $self->_check_key( $key ) ) { 
        $self->logger->info( "Already have $data{link}, skipping" );
        return;
    }

    # look up opinion metadata
    $mech->get( 'http://www.ca1.uscourts.gov/opinions/opinion.php?InOpn=1' );
    $mech->submit_form( form_number => 1,
                        fields      => { OPINNUM => "${year}-${num}" }
                      );

    my $parser = HTML::TableContentParser->new;
    my $tbls = $parser->parse( $mech->response->content );

    my $date  = $tbls->[1]{rows}[1]{cells}[0]{data};
    $date =~ s{/}{-}g;
    $date =~ s{[\n\r]}{}g;
    $date =~ s{\s*$}{};

    my $title = $tbls->[1]{rows}[1]{cells}[3]{data};

    $title =~ s{&nbsp;}{}g;
    $title =~ s{[\n\r]}{}g;
    $title =~ s[<br>][]g;      # emacs really freaks on this with { }
    $title =~ s{<font size=-1>(?<dist>.+?)</font>}{}gs;
    my $district = $+{dist} || '';
    $title =~ s{\s?</?font>}{};
    $title =~ s{^\s*}{}g;
    $title =~ s{\s*$}{}g;


    my $tmpf = File::Temp->new;
    $mech->get( $data{link}, ':content_file' => $tmpf->filename );
    

    $self->logger->info( "Storing $data{link} --> $key" );

    $self->store_pdf( key      => $key,
                      datafile => $tmpf,
                      filename => $filename,
                      meta     => { description => $title,
                                    identifier  => $ident,
                                    date        => $date,
                                    district    => $district
                                  }
                    );
}

1;


